package com.liu.nb.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liu.nb.dto.UserInfoDto;
import com.liu.nb.entity.Page;
import com.liu.nb.entity.Role;
import com.liu.nb.entity.SysUser;
import com.liu.nb.mapper.UserMapper;
import com.liu.nb.service.IPageService;
import com.liu.nb.service.IRoleService;
import com.liu.nb.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author liuziyi,zk 09-02加方法
 * @since 2021-08-31
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements IUserService {
    @Autowired
    IRoleService roleService;
    @Autowired
    IPageService pageService;
    @Autowired
    BCryptPasswordEncoder passwordEncoder;
    @Resource
    private UserMapper userMapper;
    /*
    * 根据用户名获取用户信息
    * */
    @Override
    public SysUser getByUsername(String username) {
        return this.getOne(new QueryWrapper<SysUser>().eq("username",username));
    }
    /*
    * 根据用户id获取用户权限
    * */
    @Override
    public String getUserAuthorityInfo(Integer userId) {
        /*记录用户角色的字符串*/
        String authority="";
        /*获取用户的角色信息*/
        List<Role> roleList = roleService.list(new QueryWrapper<Role>().inSql("id", "SELECT role_id FROM user_role WHERE user_id =" + userId));
        if (roleList.size()>0) {
            // 这行代码的能把list集合转换成字符串并且用“ , ”隔开
            String s = roleList.stream().map(i -> "ROLE_" + i.getRoleCode()).collect(Collectors.joining(","));
            authority=s.concat(",");
        }
        /*获取用户菜单操作编码（权限编码）*/
        List<Page> pageList = pageService.list(new QueryWrapper<Page>().inSql("id","SELECT page_id FROM role_page WHERE role_id="+userId).select("perm_code"));
        if (pageList.size()>0){
            String s = pageList.stream().map(i -> i.getPermCode()).collect(Collectors.joining(","));
            authority=authority.concat(s);
        }
        return authority;
    }

    @Override
    public Boolean changeUserPassword(String username, HashMap<String, String> map) {
        SysUser sysUser = this.getByUsername(username);
        /*先判断旧密码是否正确*/
        boolean matches = passwordEncoder.matches( map.get("oldPassword"),sysUser.getPassword());
        if (matches) {
            /*新密码替代旧密码*/
            String newPassword = passwordEncoder.encode(map.get("newPassword"));
            sysUser.setPassword(newPassword);
            /*保存到数据库*/
            boolean b = this.updateById(sysUser);
            return b;
        }else {
            /*旧密码验证失败*/
            return false;
        }
    }

    @Override
    public IPage<SysUser> getUser(Integer pageCurrent, Integer pageSize, String name, Integer state) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<SysUser> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageCurrent,pageSize);//设置分页参数
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(ObjectUtil.isNotNull(name),"name",name).eq(ObjectUtil.isNotNull(state),"state",state);//设置查询条件
        IPage<SysUser> userPage = userMapper.selectPage(page,queryWrapper);
        return userPage;
    }

    @Override
    public Integer getId(String name) {
        return (this.getOne(new QueryWrapper<SysUser>().eq("name",name))).getId();
    }

    @Override
    public UserInfoDto getUserInfoByName(String username) {
        SysUser user = this.getOne(new QueryWrapper<SysUser>().eq("username", username));
        List<Role> roleList = roleService.list(new QueryWrapper<Role>().inSql("id", "SELECT role_id FROM user_role WHERE user_id =" + user.getId()));
        String roles = roleList.stream().map(i -> i.getName()).collect(Collectors.joining(","));
        return new UserInfoDto(user.getName(),roles);
    }
}
